import os
from feishu_api import upload_media, batch_create_records

BASE_URL = 'https://open.feishu.cn'
APP_TOKEN = 'ZbnybBxZPatbNYsmjAvcVk2dnGh'
TABLE_ID = 'tbl8Dl8miTwQHpNA'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer t-g10453geGHZSIQ22Q4VQ7OFHZTGE4FLOP2CKN2RB'
}

def main():
    dir_path = 'C:/Users/hwjoy/Desktop/济宁英氏特价'
    # 获取目录下的所有jpg文件，除了文件夹
    file_list = [os.path.join(dir_path, f) for f in os.listdir(dir_path) 
             if os.path.isfile(os.path.join(dir_path, f)) and f.lower().endswith('.jpg')]
    records = []
    # 遍历文件列表
    for file_path in file_list:
        # 上传图片
        file_name = os.path.basename(file_path)
        file_name_without_ext = os.path.splitext(file_name)[0]  # 剔除文件后缀
        file_token = upload_media(file_path, APP_TOKEN)
        record = {
            "fields": {
                "商品名称": file_name_without_ext,
                "商品图片": [{"file_token": file_token}],
                "商品规格1-名称": "颜色",
                "商品规格2-名称": "尺码",
                "库存": "1",
            }
        }
        records.append(record)
        print(f"商品记录 {record}")

    # 每10条记录创建一个表格if records and len(records) > 0:
    print(f"新增 {len(records)} 商品记录...")
    # 每次最多上传1000条
    batch_size = 1000
    for i in range(0, len(records), batch_size):
        batch_records = records[i:i + batch_size]
        if batch_create_records(batch_records, APP_TOKEN, TABLE_ID):
            print(f"新增商品记录 {len(batch_records)} 条成功")
        else:
            print("新增商品记录失败")

if __name__ == '__main__':
    main()
    input("按任意键退出...")
